var websock = null;
let rec; //断线重连后，延迟5秒重新创建WebSocket连接  rec用来存储延迟请求的代码
let isConnect = false; //连接标识 避免重复连接

var globalCallback = new Map();

let createWebSocket = (paramsUrl) => {
  try {
    initWebSocket(paramsUrl); //初始化websocket连接
  } catch (e) {
    //console.log("尝试创建连接失败");
    reConnect(); //如果无法连接上webSocket 那么重新连接！可能会因为服务器重新部署，或者短暂断网等导致无法创建连接
  }
};

//定义重连函数
let reConnect = () => {
  //console.log("尝试重新连接");
  if (isConnect) return; //如果已经连上就不在重连了
  rec && clearTimeout(rec);
  rec = setTimeout(function () { // 延迟5秒重连  避免过多次过频繁请求重连
    createWebSocket();
  }, 5000);
};

//设置关闭连接
let closeWebSocket = () => {
  websock.close();
};

// 初始化websocket
function initWebSocket(paramsUrl) {
  // ws地址
 const wsUri = import.meta.env.VITE_APP_SOKET_API+paramsUrl;
  websock = new WebSocket(wsUri)
  websock.onmessage = function (e) {
    websocketonmessage(e)
  }
  websock.onopen = function () {
    isConnect = true;
    //console.log('连接成功');
  }

  // 连接发生错误的回调方法
  websock.onerror = function () {
    //console.log('WebSocket连接发生错误')
    isConnect = false; //连接断开修改标识
    reConnect(); //连接错误 需要重连
  }
}

// 实际调用的方法
function sendSock(agentData, callback, key) {
  if (!websock){
    initWebSocket()
  }
  globalCallback.set(key,callback)
  if (websock.readyState === websock.OPEN) {
    // 若是ws开启状态
    websocketsend(agentData,callback,key)
  } else if (websock.readyState === websock.CONNECTING) {
    // 若是 正在开启状态，则等待1s后重新调用
    setTimeout(function () {
      sendSock(agentData, callback,key)
    }, 2000)
  } else {
    // 若未开启 ，则等待1s后重新调用
    setTimeout(function () {
      sendSock(agentData, callback,key)
    }, 2000)
  }
}

function getSock(key,callback) {
  globalCallback.set(key,callback)
}


// 数据接收
function websocketonmessage(e) {
  //console.log(e)
  let ret = e.data

  if (ret.msg === "websocket connect success") { 

  } else {
    if (ret.method === "webSocket_device_transport"){

      const callback = globalCallback.get(ret.sn)

      if (callback && typeof callback === "function")

      callback(ret);
    }else if(ret.method === "webSocket_device_alarm"){ 
      const callback = globalCallback.get('deviceAlert')
      if (callback && typeof callback === "function")
      callback(ret);
    }
  }

  // globalCallback(JSON.parse(e.data))
  function decodeUnicode(str) {
    str = str.replace(/\\/g, "%");
    //转换中文
    str = unescape(str);
    //将其他受影响的转换回原来
    str = str.replace(/%/g, "\\");
    //对网址的链接进行处理
    str = str.replace(/\\/g, "");
    return str;
  }
}

// 数据发送
function websocketsend(agentData) {
  websock.send(JSON.stringify(agentData))
}

// 关闭
function websocketclose(e) {
  //console.log(e)
  isConnect = false ; //断开后修改标识
  //console.log('connection closed (' + e.code + ')')
}

// 创建 websocket 连接
function websocketOpen(e) {
  isConnect = true
  //console.log('连接成功')
}

//登录成功后再建立连接
//initWebSocket()

// 将方法暴露出去
export {
  sendSock,
  getSock,
  createWebSocket,
  closeWebSocket,
  initWebSocket
}